<template>
  <h2>农产品上架</h2>
  <br>
  <el-form :model="produceForm" ref="produceFormRef" label-width="120px">
    <el-form-item label="农产品图片">
      <el-upload
          class="uploadGoodsP"
          :action="staticResourcesUrl+'/produce/uploadImg'"
          ref="uploadRef"
          :auto-upload="false"
          :multiple="true"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="handChange"
          list-type="picture-card"
          :file-list="imgList"
      >
        <el-icon><plus /></el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" alt="Preview Image" style="max-width: 40vw;max-height: 40vh" />
      </el-dialog>
    </el-form-item>
    <el-form-item label="农产品名称" prop="produceName" >
      <el-input
          v-model.trim="produceForm.produceName"
          placeholder="请输入您要上架的农产品名称"
          :clearable="true"
          maxlength="32"
          show-word-limit
      />
    </el-form-item>
    <el-form-item label="农产品类型">
      <el-select v-model="produceForm.produceType" placeholder="请选择" >
        <el-option
            v-for="item in produceTypeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="农产品单价" porop="price">
      <el-input-number clearable="true" v-model="produceForm.price" :precision="2" :step="1.0" :min="0" :max="999.99" />
    </el-form-item>
    <el-form-item label="农产品份数" porop="count">
      <el-input-number clearable="true" v-model="produceForm.count" :precision="0" :step="1" :min="0" :max="999" />
    </el-form-item>
    <el-form-item label="农产品描述" porop="describe">
      <el-input
          v-model="produceForm.describe"
          type="textarea"
          placeholder="为您的农产品做一个简要的描述"
          :clearable="true"
          maxlength="255"
          show-word-limit
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">提交信息</el-button>
      <el-button type="danger" @click="resetForm">重置表单</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {ref, reactive, getCurrentInstance} from 'vue'
import request from "@/http/request";

export default {
  name: "AddProduce",
  data() {
    return {
      produceTypeList: [],
      produceID: "",
      imgList: [],
      produceFormRef: ref(null),
      dialogImageUrl: "",
      dialogVisible: false,
      produceForm: reactive({
        produceName: "",
        produceType: "",
        describe: "",
        price:0,
        count:0,
      }),
    }
  },
  methods: {
    getProduceType() {
      request({
        url: "/produce/getProduceType",
        method: "get",
      }).then((response) => {
        if (response.code === 200) {
          this.produceTypeList = response.data;
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    },
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },
    handleRemove(uploadFile){
      if (uploadFile.img) {
        request({
          url: "/produce/deleteImg",
          method: "post",
          data: {
            fileName: uploadFile.img.substring(uploadFile.img.lastIndexOf("/")+1),
          },
        }).then((response) => {
          if (response.code === 200) {
            this.$tipUtil.successTip(response.msg);
          } else {
            this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    handChange(UploadFile, UploadFiles) {
      if (UploadFile.raw) {
        const isJPG = UploadFile.raw.type === 'image/jpg';
        const isJPEG = UploadFile.raw.type === 'image/jpeg';
        const isPNG = UploadFile.raw.type === 'image/png';
        const isSizeLt = UploadFile.raw.size / 1024 / 1024 < 20;
        if (!isJPG && !isJPEG && !isPNG) {
          this.$message.error('上传头像图片只能是 jpg/jpeg/png 格式!');
          UploadFiles.splice(UploadFiles.indexOf(UploadFile), 1);
        }
        if (!isSizeLt) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
          UploadFiles.splice(UploadFiles.indexOf(UploadFile), 1);
        }
      }
    },
    submitUpload() {
      const _this = this;
      if (_this.produceID!=="" && _this.imgList.length > 0){
        const formData = new FormData();
        // 你可以使用FormData.append来添加键/值对到表单里面；
        _this.imgList.forEach((file) => {
          if (file.raw) {
            formData.append('file', file.raw);
          }
        })
        formData.append("uuid", _this.produceID);
        request({
          "url": "produce/uploadImg",
          "method": "post",
          data: formData,
        }).then( (response)=> {
          if (response.code === 200) {
            _this.$tipUtil.successTip(response.msg);
            this.$router.replace({
              name: 'ManageProduce',
            })
          } else if (response.code === 521) {
            _this.$tipUtil.warningTip(response.msg);
          } else {
            _this.$tipUtil.errTip(response.msg);
          }
        })
      }
    },
    resetForm: function() {
      this.$refs['produceFormRef'].resetFields();
      this.produceForm.price = 0;
      this.produceForm.describe = "";
    },
    submit() {
      request({
        url: "/produce/addProduce",
        method: "post",
        data: {
          produceName: this.produceForm.produceName,
          produceType: this.produceForm.produceType,
          price: this.produceForm.price.toString(),
          count: this.produceForm.count.toString(),
          describe: this.produceForm.describe,
        },
      }).then((response) => {
        if (response.code === 200) {
          this.produceID = response.data.produceID;
          this.submitUpload();
          this.$tipUtil.successTip(response.msg);
        } else {
          this.$tipUtil.errTip(response.msg);
        }
      })
    }
  },
  setup() {
    const { appContext : { config: { globalProperties } } } = getCurrentInstance();
    const staticResourcesUrl = globalProperties.$staticResourcesUrl;
    return {
      staticResourcesUrl,
    }
  },
  mounted() {
    this.getProduceType();
  }
}
</script>

<style scoped>
</style>